const { prisma } = require('../config/prisma');
const { CozeService } = require('../services/coze.service');

/**
 * 生成奖励图片
 */
const generateImage = async (req, res) => {
  try {
    // 设置默认积分成本为50
    const cost_per_image = 50;

    // 检查用户积分是否足够
    const user = await prisma.user.findUnique({
      where: { id: req.user.id }
    });

    if (!user || user.points < cost_per_image) {
      return res.status(400).json({
        code: 1001,
        message: '积分不足',
        data: {
          points_balance: user ? user.points : 0,
          points_cost: cost_per_image
        }
      });
    }

    // 调用Coze API生成图片
    const cozeServiceInstance = new CozeService();
    const imageUrl = await cozeServiceInstance.generateImage();
    console.log('Coze API image response:', { image_url: imageUrl });

    if (!imageUrl) {
      console.error('No image URL found in response');
      throw new Error('No image URL in response');
    }

    console.log('Using image URL:', imageUrl);

    // 开启事务：创建图片记录并扣除积分
    const result = await prisma.$transaction(async (prisma) => {
      // 再次检查积分是否足够（防止并发情况）
      const currentUser = await prisma.user.findUnique({
        where: { id: req.user.id }
      });

      if (!currentUser || currentUser.points < cost_per_image) {
        throw new Error('Insufficient points');
      }

      // 创建图片记录
      const imageRecord = await prisma.imageRecord.create({
        data: {
          userId: req.user.id,
          pointsCost: cost_per_image,
          imageUrl
        }
      });

      // 扣除用户积分
      const updatedUser = await prisma.user.update({
        where: { id: req.user.id },
        data: {
          points: {
            decrement: cost_per_image
          }
        }
      });

      // 创建积分记录
      await prisma.pointsRecord.create({
        data: {
          userId: req.user.id,
          points: -cost_per_image,
          type: 2, // 生成图片消耗
          remark: '生成奖励图片'
        }
      });

      return {
        imageRecord,
        pointsBalance: updatedUser.points
      };
    });

    res.json({
      code: 0,
      data: {
        id: result.imageRecord.id,
        image_url: result.imageRecord.imageUrl,
        points_cost: cost_per_image,
        points_balance: result.pointsBalance
      },
      message: '生成成功'
    });
  } catch (error) {
    console.error('Generate image error:', error);
    if (error.message === 'Points configuration not found') {
      return res.status(500).json({
        code: 500,
        message: '系统配置错误'
      });
    }
    if (error.message === 'Insufficient points') {
      return res.status(400).json({
        code: 1001,
        message: '积分不足',
        data: {
          points_balance: user ? user.points : 0,
          points_cost: cost_per_image
        }
      });
    }
    res.status(500).json({
      code: 5001,
      message: '图片生成失败，请重试'
    });
  }
};

/**
 * 获取图片记录列表
 */
const getImageRecords = async (req, res) => {
  try {
    const { page = 1, size = 20 } = req.query;
    const skip = (page - 1) * size;

    const [total, records] = await Promise.all([
      prisma.imageRecord.count({
        where: { userId: req.user.id }
      }),
      prisma.imageRecord.findMany({
        where: { userId: req.user.id },
        orderBy: { createdAt: 'desc' },
        skip,
        take: parseInt(size),
        select: {
          id: true,
          imageUrl: true,
          pointsCost: true,
          createdAt: true
        }
      })
    ]);

    res.json({
      code: 0,
      data: {
        total,
        list: records.map(record => ({
          id: record.id,
          image_url: record.imageUrl,
          points_cost: record.pointsCost,
          created_at: record.createdAt
        }))
      }
    });
  } catch (error) {
    console.error('Get image records error:', error);
    res.status(500).json({
      code: 500,
      message: '获取图片记录失败'
    });
  }
};

/**
 * 删除图片记录
 */
const deleteImageRecord = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查记录是否存在且属于当前用户
    const record = await prisma.imageRecord.findFirst({
      where: {
        id,
        userId: req.user.id
      }
    });

    if (!record) {
      return res.status(404).json({
        code: 404,
        message: '记录不存在'
      });
    }

    // 删除记录
    await prisma.imageRecord.delete({
      where: { id }
    });

    res.json({
      code: 0,
      message: '删除成功'
    });
  } catch (error) {
    console.error('Delete image record error:', error);
    res.status(500).json({
      code: 500,
      message: '删除失败'
    });
  }
};

module.exports = {
  generateImage,
  getImageRecords,
  deleteImageRecord
}; 